from flask import Flask, g, jsonify
from flask_auth_mgr import SimpleAuthMgr

#--------------------#
app = Flask(__name__)
app.config['SECRET_KEY'] = 'the quick brown fox jumps over the lazy dog'
auth = SimpleAuthMgr(app.config['SECRET_KEY'], expires_in=600)

#--------------------#
users = {
    "john": auth.generate_password_hash("hello"),
    "susan": auth.generate_password_hash("bye")
}

#--------------------#
@auth.basic.verify_password
def verify_password(user, password):
    g.user = None
    if user not in users:
        return False
    if auth.check_password_hash(users.get(user), password):
        g.user = user
        return True
    return False

@auth.token.verify_token
def verify_token(token):
    data = auth.token_data(token)
    if data is None:
        return False
    g.user = data['user']
    return True

#--------------------#
@app.route('/token')
@auth.basic.login_required
def route_token():
    token_data = {
        'user': g.user,
    }

    data = {
        'user': g.user,
        'token': auth.generate_token(token_data)
    }
    return jsonify(data)

@app.route('/need_pwd')
@auth.basic.login_required
def route_need_pwd():
    return 'this page need password: %s\n' % g.user

@app.route('/need_token')
@auth.token.login_required
def route_need_token():
    return 'this page need token: %s\n' % g.user

@app.route('/need_pwd_token')
@auth.multi.login_required
def route_need_pwd_token():
    return 'this page need password or token: %s\n' % g.user

#--------------------#

if __name__ == '__main__':
    app.run(debug=True)
#--------------------#
    